package com.ysstech.common.util.fileutil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.ysstech.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 文件装换工具
 */
@Slf4j
public class FileUtil extends FileUtils {


    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * MultipartFile装换成file
     */
    public static File getFile(MultipartFile multipartfile) throws Exception {
        //不生成临时文件，直接转换
        File file = null;
        try {
            if (null != multipartfile && !multipartfile.isEmpty()) {
                CommonsMultipartFile commonsmultipartfile = (CommonsMultipartFile) multipartfile;
                DiskFileItem diskFileItem = (DiskFileItem) commonsmultipartfile.getFileItem();
                file = diskFileItem.getStoreLocation();
            }
        } catch (Exception e) {
            logger.error(e.toString());
            throw new Exception("MultipartFile转换file失败!");
        }
        return file;
    }

    /**
     * MultipartFile装换成file
     */
    public static File MultipartFileToFile(MultipartFile multipartFile) throws Exception {
        File file = null;
        try {
            InputStream ins = null;
            ins = multipartFile.getInputStream();
            file = new File(multipartFile.getOriginalFilename());
            inputStreamToFile(ins, file);
            ins.close();
        } catch (Exception e) {
            logger.error(e.toString());
            throw new Exception("MultipartFile转换file失败!");
        }
        return file;
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    public static void inputStreamToFile(InputStream ins, File file) throws Exception {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            logger.error(e.toString());
            throw new Exception("InputStream转换file失败!");
        }
    }


    /**
     * 保存文件
     *
     * @param file     文件
     * @param path     文件存放路径
     * @param fileName 文件名
     * @return
     */
    public static boolean upload(MultipartFile file, String path, String fileName) throws Exception {
        String realPath = path + "/" + fileName;
        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(dest);
        } catch (Exception e) {
            logger.error(e.toString());
            throw new Exception("保存文件失败，请稍后重试!");
        }
        return true;
    }

    /**
     * 读取文件路径 filepath
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(String filepath) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<List<Object>> readAll = reader.read();
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<List<Object>> readAll = reader.read();
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file, int sheetIndex) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetIndex);
            List<List<Object>> readAll = reader.read();
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file, String sheetName) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetName);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = 1; i < readAll.size(); i++) {
                int size = readAll.get(0).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }

    /**
     * 读取文件路径 filepath
     * 读取为Map列表，默认第一行为标题行，Map中的key为标题，value为标题对应的单元格值。
     */
    public static List<Map<String, Object>> readerExcelListMap(String filepath) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<Map<String, Object>> readAll = reader.readAll();
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取为Map列表，默认第一行为标题行，Map中的key为标题，value为标题对应的单元格值。
     */
    public static List<Map<String, Object>> readerExcelListMap(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Map<String, Object>> readAll = reader.readAll();
            return readAll;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件filepath
     * 读取为Bean列表，Bean中的字段名为标题，字段值为标题对应的单元格值。
     *
     * @param filepath
     * @param tclass
     * @return
     * @throws Exception
     */
    public static List<Class> readerExcelBean(String filepath, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<Class> all = reader.readAll(tclass);
            return all;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取为Bean列表，Bean中的字段名为标题，字段值为标题对应的单元格值。
     *
     * @param file
     * @param tclass
     * @return
     * @throws Exception
     */
    public static List<Class> readerExcelBean(File file, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Class> all = reader.readAll(tclass);
            return all;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    public static List<Map<String, Object>> readerExcelListMapObject(File file, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Map<String, Object>> all = reader.readAll();
            return all;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    public static List<List<Object>> readerExcelListObject(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<List<Object>> all = reader.read();
            return all;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取dbf内容，显示到前台
     * 包装的和读取execl一样，前台统一解析
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
  /*  public static List<Object> readerDBF(MultipartFile multipartFile, Class beanType) throws Exception {
        DBFReader reader = null;//从dbf中获取内容
        List<Object> list = new ArrayList<Object>();
        try {
            CommonsMultipartFile cFile = (CommonsMultipartFile) multipartFile;
            DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
            InputStream inputStream = fileItem.getInputStream();
            reader = new DBFReader(inputStream);//将文件从文件流中读入。
            reader.setCharactersetName("GBK"); //解决中文乱码问题
            Object[] rowObjects = null;
            Field[] fields = beanType.getDeclaredFields();
            while ((rowObjects = reader.nextRecord()) != null) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 0; i < rowObjects.length; i++) {
                    map.put(fields[i].getName(), rowObjects[i]);
                }
                list.add(BeanUtil.mapToBean(map, beanType, false));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取DBF文件失败，请稍后重试！");
        }
        return list;
    }*/


    /**
     * 读取dbf内容，显示到前台
     * 包装的和读取execl一样，前台统一解析
     *
     * @param multipartFile
     * @return
     * @throws SQLException
     */
    /*public static List<List<Object>> readerDBF(MultipartFile multipartFile) throws Exception {
        DBFReader reader = null;//从dbf中获取内容
        List<List<Object>> list = null;
        try {
            CommonsMultipartFile cFile = (CommonsMultipartFile) multipartFile;
            DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
            InputStream inputStream = fileItem.getInputStream();
            reader = new DBFReader(inputStream);//将文件从文件流中读入。
            reader.setCharactersetName("GBK"); //解决中文乱码问题
            Object[] rowObjects = null;
       *//*     list = new ArrayList<>();
            for (int i = 0; i < reader.getFieldCount(); i++) {
                list.add(reader.getField(i).getName());
            }
            all.add(list);*//*
            while ((rowObjects = reader.nextRecord()) != null) {
                List<Object> list2 = new ArrayList<>();
                for (int i = 0; i < rowObjects.length; i++) {
                    list2.add(rowObjects[i]);
                }
                list.add(list2);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取DBF文件失败，请稍后重试！");
        }
        return list;
    }*/
    public static List<Object> readerTxt(MultipartFile multipartFile) throws Exception {
        return readerTxt(multipartFile, "UTF-8");
    }

    public static List<Object> readerTxt(MultipartFile multipartFile, String charsetName) throws Exception {
        List<Object> list = new ArrayList<>();
        File file = null;
        try {
            if (null == multipartFile || multipartFile.isEmpty()) {
                return list;
            }
            file = FileUtil.MultipartFileToFile(multipartFile);
            if (null == file) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName));
            String lineTxt = null;
            while ((lineTxt = br.readLine()) != null) {
                list.add(lineTxt);
            }
            br.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取TXT文件失败，请稍后重试！");
        } finally {
            FileUtil.delteTempFile(file);
        }
        return list;
    }

    /**
     * 读取xml方法
     *
     * @param multipartFile
     * @param beanClass
     * @param <T>
     * @return
     * @throws SQLException
     */

    public static <T> T readXml(MultipartFile multipartFile, Class<T> beanClass) throws Exception {
        if (null == multipartFile || multipartFile.isEmpty()) {
            return null;
        }
        File newfile = null;
        try {
            //1.创建dom4j核心对象SAXReader
            SAXReader sax = new SAXReader();
            //2.使用SAXReader中read方法读取xml文档,生成Document对象
            newfile = FileUtil.MultipartFileToFile(multipartFile);
            if (null == newfile) {
                throw new BusinessException("获取文件数据失败，请稍后重试！");
            }
            Document docu = sax.read(newfile);
            //3.使用Document中方法getRootElement获取根元素Element
            Element rootElement = docu.getRootElement();
            //4.使用Element中的方法elements获取所有bean元素
            List<Element> onelist = rootElement.elements();
            //5.遍历包含bean元素的集合,获取每一个bean元素
            Map<String, Object> mapone = new HashMap<>();
            List<Object> listd = new ArrayList<>();
            for (Element one : onelist) {
                mapone.put(one.getName(), one.getTextTrim()); //一级标签的key和value
                List<Element> twolist = one.elements(); //取到二级标签
                for (Element two : twolist) { //二级标签没有值
                    Map<String, Object> mapthree = new HashMap<>();
                    List<Element> threelist = two.elements(); //三级
                    for (Element three : threelist) {
                        mapthree.put(three.getName(), three.getTextTrim()); //三级标签的key和value
                    }
                    listd.add(BeanUtil.mapToBean(mapthree, beanClass, false));
                    mapone.put(one.getName(), listd);  //Components  Component list
                }
            }
            return BeanUtil.mapToBean(mapone, beanClass, false);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取XML文件失败，请稍后重试！");
        } finally {
            FileUtil.delteTempFile(newfile);
        }
    }

    /**
     * 读取properties配置文件
     *
     * @param resourceName
     */
    public static Map<String, String> readProperty(String resourceName) throws Exception {
        Map<String, String> map = null;
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(resourceName);
            if (null == properties) {
                return null;
            }
            map = new HashMap<>();
            //遍历取值
            Set<Object> objects = properties.keySet();
            for (Object object : objects) {
                if (null == object) {
                    continue;
                }
                map.put(object.toString(), properties.getProperty((String) object));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception("读取" + resourceName + "文件失败，请稍后重试！");
        }
        return map;
    }

    public static String separator = "/";

    /**
     * 替换反斜杠为正斜杠
     *
     * @param str 要替换的字符串
     * @return {@link String}
     */
    public static String replaceSeparator(String str) {
        return StringUtils.isEmpty(str) ? "" : str.replaceAll("\\\\", separator);
    }

    /**
     * 获取当前文件的父路径
     *
     * @param filePath 文件路径
     * @return {@link String} 父级路径
     */
    public static String getParentPath(String filePath) {
        String s = replaceSeparator(filePath);
        return s.substring(0, s.lastIndexOf(separator));
    }


    public static void main(String[] args) throws Exception {
        List<List<Object>> list = FileUtil.readerExcelListObject(new File("C:\\SVN文件\\基础数据模板表.xlsx"));
    }
}
